/********************************************
 * 功能说明: 
 * 模块名称: 
 * 系统名称: 
 * 软件版权: 北京银杉金服科技有限公司
 * 系统版本: 1.0.0
 * 开发人员: zhangfb
 * 开发时间: 2019/3/18 21:29
 * 审核人员: 
 * 相关文档: 
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.hyacinth;

import com.hyacinth.factory.DefaultObjectFactory;
import com.hyacinth.factory.ObjectFactory;
import com.hyacinth.reflact.DefaultReflectorFactory;
import com.hyacinth.wrapper.DefaultObjectWrapperFactory;
import com.hyacinth.wrapper.ObjectWrapperFactory;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Properties;

/**
 * 目标对象工具类
 * <p>用户将系统对象转换为目标对象</p>
 * @author zhangfb
 * @version 1.0.0.1
 * @since JDK 1.8
 */
public final class SystemMetaObject {

    public static final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory();
    public static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory();
    public static final MetaObject NULL_META_OBJECT = MetaObject.forObject(NullObject.class, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY, new DefaultReflectorFactory());


    private SystemMetaObject() {
        // Prevent Instantiation of Static Class
    }

    private static class NullObject {
    }

    /**
     * 获取目标对象
     * @param object 原始对象
     * @return 目标对象
     */
    public static MetaObject forObject(Object object) {
        return MetaObject.forObject(object, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY, new DefaultReflectorFactory());
    }

    /**
     * 对象设置属性
     * @param object
     * @param properties
     */
    public static void setProperties(Object object, Properties properties) {
        MetaObject metaObject = forObject(object);
        for (Object key : properties.keySet()) {
            String propertyName = (String) key;
            String value = (String) properties.get(key);
            metaObject.setValue(propertyName, convertValue(metaObject, propertyName, value));
        }
    }

    private static Object convertValue(MetaObject metaObject, String propertyName, String value) {
        Object convertedValue = value;
        Class<?> targetType = metaObject.getSetterType(propertyName);
        if (targetType == Integer.class || targetType == int.class) {
            convertedValue = Integer.valueOf(value);
        } else if (targetType == Long.class || targetType == long.class) {
            convertedValue = Long.valueOf(value);
        } else if (targetType == Boolean.class || targetType == boolean.class) {
            convertedValue = Boolean.valueOf(value);
        } else if (targetType == BigDecimal.class) {
            convertedValue = new BigDecimal(value);
        } else if (targetType == Double.class || targetType == double.class) {
            convertedValue = Double.valueOf(value);
        } else if (targetType == Date.class) {
            // TODO 时间格式转换，推荐使用JDK8
        }
        return convertedValue;
    }
}
